import React, { Component } from 'react';
import { GLOBAL } from '../../../../config/global';
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  PixelRatio,
  FlatList,
  Alert
} from "react-native";
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../../utils/toast';
import HTTP from '../../../../utils/http';
import { API, API_GENERATE } from '../../../../config/api';
import { NavigationEvents } from 'react-navigation';
import { RefuseModal } from '../../../../component/ModalVerifylComponent.js';
import Permission from '../../../../utils/permission';

const scale = GLOBAL.SCALE;
const arrowIcon = require('../../../../imgs/arrow.png')

export class OperatePlanApprovalListPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      title: '经营计划待审列表',
      headerTintColor: style.color.white,
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
      headerRight: (<Image style={{ marginLeft: 18 * scale, width: 9 * scale, height: 16 * scale }} source={require('../../../../imgs/goBackEmpty.png')} />),
      headerStyle: {
        elevation: 0,
        backgroundColor: style.color.themeColor,
      },
      headerTitleStyle: {
        flex: 1,
        textAlign: 'center'
      }
    }
  }

  constructor(props) {
    super(props);
    this.state = {
      status: 'data',
      listData: [],
      tabIndex: 0,
      selectAll: false,
      refreshIcon: false,
    };
    this.totalPage = 1;
    this.reload = true; // 判断是整个页面刷新还是下拉刷新
    this.selectedProduct = []; // 选中的商品
    this.planParams = {
      isNew: 0  // 0-正常提报 1-临增
    }
    this.pageParams = {
      pageNo: 1,
      pageSize: 10,
    }
  }

  async componentWillMount () {
    this.initPage();
  }

  // 初始化计划提报和临增计划列表
  initPage = async (refreshIcon) => {
    this.setState({
      status: refreshIcon ? 'data' : 'loading',
      refreshIcon: !!refreshIcon
    })
    let responseData = await HTTP.GET(API_GENERATE(API.OPERATE_PLAN_APPROVAL_LIST), this.planParams);
    if (responseData) {
      this.setState({
        listData: responseData,
        status: responseData.length > 0 ? 'data' : 'empty',
        refreshIcon: false
      })
    } else {
      this.setState({
        status: 'error'
      })
    }
  }

  // 初始化当月变更计划列表
  initChangedPlan = async () => {
    this.setState({
      status: this.reload ? 'loading' : 'data',
      refreshIcon: !this.reload && this.pageParams.pageNo == '1'
    })
    let res = await HTTP.POST(API_GENERATE(API.OPERATE_PLAN_CHANGED_LIST), this.pageParams);
    if (res) {
      this.totalPage = res.totalPage;
      res.rows.forEach(item => {
        item.selected = false;
      })
      if (this.pageParams.pageNo == '1') this.selectedProduct = [];
      this.setState({
        status: res.rows.length > 0 ? 'data' : 'empty',
        listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
        refreshIcon: false,
        selectAll: false
      })
    } else {
      this.setState({
        refreshIcon: false,
        status: 'error'
      })
    }
  }

  // 下拉刷新当月变更计划
  refresh = () => {
    this.pageParams.pageNo = 1;
    this.reload = false;
    this.initChangedPlan();
  }

  // 刷新当月变更计划
  reloadPage = () => {
    this.pageParams.pageNo = 1;
    this.reload = true;
    this.initChangedPlan();
  }

  // 加载更多当月变更计划
  loadMore = () => {
    if (this.totalPage > this.pageParams.pageNo) {
      this.pageParams.pageNo++;
      this.reload = false;
      this.initChangedPlan();
    }
  }

  onErrorRefresh = () => {
    let { tabIndex } = this.state;
    if (tabIndex != 2) {
      this.initPage();
    } else {
      this.reloadPage();
    }
  }

  // 选择变更计划
  selectProduct = (index, data) => {
    let { selected, changeId } = data;
    let { listData } = this.state;
    let selectAll = true;
    listData.forEach((item, i) => {
      if (index == i) {
        item.selected = !selected;
        if (item.selected) {
          this.selectedProduct.push(changeId);
        } else {
          let index = this.selectedProduct.indexOf(changeId);
          this.selectedProduct.splice(index, 1)
        }
      }
      if (!item.selected) selectAll = false;
    })
    this.setState({ listData, selectAll })
  }

  // 全选
  selectAll = () => {
    let { listData, selectAll } = this.state;
    let toggleSelect = !selectAll;
    this.selectedProduct = [];
    listData.forEach((item, index) => {
      item.selected = toggleSelect;
      if (toggleSelect) {
        this.selectedProduct.push(item.changeId);
      }
    })
    this.setState({ listData, selectAll: toggleSelect })
  }

  // 驳回
  rejectConfirm = (remark) => {
    this.setState({
      showRejectModal: false
    }, () => {
      if (remark) {
        this.approve({ audit: 0, remark });
      } else {
        ToastUtil.showWarning('请填写驳回原因！');
      }
    })

  }

  // 审批通过确认
  approveConfirm = () => {
    if (this.selectedProduct.length > 0) {
      Alert.alert('提示', '是否确认审批通过？', [
        { text: '取消' },
        { text: '确定', onPress: () => { this.approve({ audit: 1 }) } },
      ]);
    } else {
      ToastUtil.showWarning('请选择商品！');
    }
  }

  // 审批
  approve = async (data) => {
    let params = {
      planChangeIds: this.selectedProduct
    }
    let requestParams = Object.assign(params, data);
    let text = data.audit == 0 ? '驳回' : '通过';
    this.setState({
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.OPERATE_PLAN_CHANGED_APPROVAL), requestParams);
    if (res) {
      ToastUtil.showSuccess(`${text}成功`).then(() => {
        this.reloadPage()
      })
    } else {
      this.setState({
        status: 'data'
      }, () => {
        ToastUtil.showWarning(`${text}失败`);
      })
    }
  }

  _renderListItem = (data) => {
    let item = data.item;
    let { tabIndex } = this.state;
    // x月（统销）待审
    let itemTitle = tabIndex == 0 ? `${item.month.substr(-2, 2) || ''}月${item.bizTypeName}资源计划 待审` : `${item.month.substr(-2, 2) || ''}月临增计划(${item.bizTypeName}) 待审`;

    return (
      <View style={{ marginTop: 15 * scale }}>
        <View style={{ marginBottom: 7 * scale, flexDirection: 'row', justifyContent: 'flex-end' }}>
          <Text style={styles.itemLightText}>{item.createTime}</Text>
        </View>
        <TouchableOpacity activeOpacity={.6} style={styles.itemWrap} onPress={() => {
          this.props.navigation.navigate('OperatePlanApprovalDetailPage', {
            approveInfo: item,
            isNew: tabIndex // 是否临增
          })
        }}>
          <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative', marginBottom: 10 * scale, paddingRight: 20 * scale }}>
            <View style={[styles.itemType, item.planType == 'S' ? { backgroundColor: style.color.themeColor } : '']}>
              <Text style={{ color: '#fff', fontSize: 12 * scale }}>{item.planTypeName.slice(0, 1)}({item.bizTypeName})</Text>
            </View>
            <Text numberOfLines={1} style={{ color: '#272727', fontSize: 14 * scale, flex: 1 }}>{itemTitle}</Text>
            <Image style={{ backgroundColor: 'red' }} source={arrowIcon} style={styles.arrowIcon} />
          </View>
          <View style={{ flexDirection: 'row', }}>
            <View style={{ flex: 2 }}>
              <Text style={styles.itemLightText}>提报部门</Text>
              <Text numberOfLines={2} style={styles.itemDarkText}>
                {
                  item.organNameList && item.organNameList.length > 0 ?
                    item.organNameList.map((organName, i) => {
                      return (
                        (i == item.organNameList.length - 1) ? organName : organName + '、'
                      )
                    })
                    : null
                }
              </Text>
            </View>
            <View style={{ flex: 1 }}>
              <Text style={styles.itemLightText}>计划总量(吨)</Text>
              <Text numberOfLines={1} style={styles.itemDarkText}>{item.suggestWeight}</Text>
            </View>
          </View>
        </TouchableOpacity>
      </View>
    )
  }

  _renderChangedItem = (data) => {
    let item = data.item;
    const checkOn = require('../../../../imgs/checkOn.png');
    const checkOff = require('../../../../imgs/checkOff.png');
    let suggestWeight = parseFloat(item.suggestWeight) || 0;
    let newWeight = parseFloat(item.newWeight) || 0;
    let rangeWeight = newWeight - suggestWeight;
    return (
      <View style={{ marginTop: 15 * scale }}>
        <View style={{ marginBottom: 7 * scale, flexDirection: 'row', justifyContent: 'flex-end' }}>
          <Text style={styles.itemLightText}>{item.createTime}</Text>
        </View>
        <View activeOpacity={.6} style={[styles.itemWrap, { paddingLeft: 34 * scale }]} >
          <View style={{ flexDirection: 'row', alignItems: 'center', position: 'relative', marginBottom: 10 * scale }}>
            <TouchableOpacity style={styles.selectIcon} activeOpacity={.8} onPress={() => { this.selectProduct(data.index, item) }}>
              <Image style={{ height: 18 * scale, width: 18 * scale }} source={item.selected ? checkOn : checkOff} />
            </TouchableOpacity>
            <Text numberOfLines={1} style={{ color: '#272727', fontSize: 14 * scale, flex: 1 }}>客户：{item.customerName || '--'}</Text>
          </View>
          <TouchableOpacity activeOpacity={.8} onPress={() => {
            this.props.navigation.navigate('OperatePlanProductDetailPage', {
              productItem: item,
              suggestWeight: item.suggestWeight,
              organName: item.organName,
              categoryName: item.categoryName,
            })
          }}>
            <Text>
              {item.categoryName || '--'}
              <Text style={{ color: '#272727' }}>|</Text>
              {item.organName || '--'}
            </Text>
            <View style={{ flexDirection: 'row', flex: 1, }}>
              <View style={styles.itemPf}>
                <Text style={styles.title}>计划量-原(吨)</Text>
                <Text style={styles.money}>{suggestWeight}</Text>
              </View>

              <View style={styles.itemPf}>
                <Text style={styles.title}>计划量-新(吨)</Text>
                <Text style={styles.money}>{newWeight}</Text>
              </View>

              <View style={styles.itemPf}>
                <Text style={styles.title}>幅度</Text>
                <Text style={[styles.money, rangeWeight >= 0 ? { color: 'green' } : { color: '#FA4516' }]}>{rangeWeight >= 0 ? '+' + rangeWeight : rangeWeight}</Text>
              </View>
            </View>
          </TouchableOpacity>
        </View>
      </View>
    )
  }

  _tabFn = (index) => {
    this.setState({
      tabIndex: index,
      listData: []
    }, () => {
      if (index == 0 || index == 1) {
        this.planParams.isNew = index;
        this.initPage();
      } else {
        this.reloadPage();
      }
    })
  }

  render () {
    let { status, listData, refreshIcon, tabIndex, selectAll, showRejectModal } = this.state;
    return (
      <View style={styles.container}>
        <NavigationEvents onWillFocus={() => {
          if (tabIndex == 2) {
            this.reloadPage()
          } else {
            this.initPage()
          }
        }} />
        <View style={styles.tabBox}>
          <Text onPress={() => { this._tabFn(0) }} style={[styles.tabBoxItem, tabIndex == 0 ? styles.tabIndex : null]}>计划提报</Text>
          {Permission.check('APL001') ? <Text onPress={() => { this._tabFn(1) }} style={[styles.tabBoxItem, tabIndex == 1 ? styles.tabIndex : null]}>当月临增计划</Text> : null}
          {Permission.check('APL002') ? <Text onPress={() => { this._tabFn(2) }} style={[styles.tabBoxItem, tabIndex == 2 ? styles.tabIndex : null]}>当月变更计划</Text> : null}
        </View>
        {
          status == 'data' ? (
            tabIndex == 2 ? (
              (<View style={[styles.listWrap, tabIndex == 2 ? { paddingBottom: 0 } : {}]}>
                <FlatList
                  data={listData}
                  renderItem={this._renderChangedItem}
                  refreshing={refreshIcon}
                  onRefresh={() => { this.refresh() }}
                  onEndReachedThreshold={0.1}
                  onEndReached={() => { this.loadMore() }}
                />
              </View>)
            ) : (
                (<View style={[styles.listWrap, tabIndex == 2 ? { paddingBottom: 0 } : {}]}>
                  <FlatList
                    data={listData}
                    renderItem={this._renderListItem}
                    refreshing={refreshIcon}
                    onRefresh={() => {
                      this.initPage(true)
                    }}
                  />
                </View>)
              )
          ) : null
        }

        {
          (tabIndex == 2 && status == 'data') ? (
            <View style={styles.operateWrap}>
              <TouchableOpacity style={{ paddingLeft: 12 * scale, paddingRight: 12 * scale, height: '100%', flexDirection: 'row', alignItems: 'center' }} onPress={() => { this.selectAll() }}>
                <Text style={selectAll ? { color: '#0E7FFD' } : { color: '#272727' }}>全选</Text>
              </TouchableOpacity>
              <View style={{ flexDirection: 'row' }}>
                <TouchableOpacity activeOpacity={.8} style={[styles.operateBtn, this.selectedProduct.length > 0 ? { backgroundColor: '#FA4516' } : '']} onPress={() => {
                  if (this.selectedProduct.length > 0) {
                    this.setState({
                      showRejectModal: true,
                    })
                  } else {
                    ToastUtil.showWarning('请选择商品！')
                  }
                }}>
                  <Text style={[{ color: '#272727', fontSize: 12 * scale }, this.selectedProduct.length > 0 ? { color: '#fff' } : '']}>驳回</Text>
                </TouchableOpacity>
                <TouchableOpacity activeOpacity={.8} style={[styles.operateBtn, this.selectedProduct.length > 0 ? { backgroundColor: '#148CFB' } : '']} onPress={() => { this.approveConfirm() }}>
                  <Text style={[{ color: '#272727', fontSize: 12 * scale }, this.selectedProduct.length > 0 ? { color: '#fff' } : '']}>通过</Text>
                </TouchableOpacity>
              </View>
            </View>
          ) : null
        }
        <RefuseModal visible={showRejectModal}
          placeholderText={'请输入驳回原因'}
          titleText={'驳回原因'}
          btnPress={(text) => {
            this.rejectConfirm(text);
          }}
          bgPress={() => {
            this.setState({
              showRejectModal: false,
            });
          }} />
        {
          status != 'data' ? (<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this.onErrorRefresh} />) : null
        }
      </View >
    )
  }
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#f5f5f5',
    flex: 1
  },
  tabBox: {
    flexDirection: 'row',
    paddingLeft: 12 * scale,
    marginTop: 12 * scale
  },
  tabBoxItem: {
    width: 90 * scale,
    height: 30 * scale,
    lineHeight: 30 * scale,
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
    color: style.color.themeColor,
    textAlign: 'center',
    marginRight: 9 * scale,
    borderRadius: 3 * scale,
    fontSize: 13 * scale
  },
  tabIndex: {
    backgroundColor: style.color.themeColor,
    color: style.color.white
  },
  listWrap: {
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    flex: 1,
    paddingBottom: 14 * scale
  },
  itemWrap: {
    backgroundColor: '#fff',
    width: '100%',
    borderRadius: 4 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    paddingBottom: 14 * scale,
    paddingTop: 14 * scale,
  },
  itemType: {
    height: 20 * scale,
    width: 58 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#FA9B22',
    borderRadius: 4 * scale,
    marginRight: 10 * scale,
  },
  arrowIcon: {
    width: 6 * scale,
    height: 12 * scale,
    position: 'absolute',
    right: 0,
    top: 2 * scale,
    right: 12 * scale,
  },
  itemLightText: {
    fontSize: 13 * scale,
    color: '#272727',
    opacity: .5,
  },
  itemDarkText: {
    color: '#272727',
    marginTop: 6 * scale,
    lineHeight: 22 * scale,
  },
  btnBox: {
    flexDirection: 'row',
    width: 110 * scale,
    justifyContent: 'center'
  },
  btnStyle: {
    width: 40 * scale,
    height: 24 * scale,
    lineHeight: 24 * scale,
    fontSize: 12 * scale,
    textAlign: 'center',
    borderRadius: 2 * scale
  },
  btnNo: {
    color: '#FA4516',
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: '#FA4516',
    marginRight: 16 * scale,
  },
  btnYes: {
    color: style.color.themeColor,
    borderWidth: 1 / PixelRatio.get(),
    borderStyle: 'solid',
    borderColor: style.color.themeColor,
  },
  title: {
    fontSize: 13 * scale,
    color: '#999',
    marginTop: 10 * scale
  },
  money: {
    fontSize: 13 * scale,
    color: '#272727',
    marginTop: 8 * scale
  },
  itemPf: {
    flex: 1
  },
  operateWrap: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 52 * scale,
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
  },
  operateBtn: {
    width: 51 * scale,
    height: 26 * scale,
    borderRadius: 2 * scale,
    marginLeft: 12 * scale,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#E9E9E9'
  },
  selectIcon: {
    position: 'absolute',
    width: 30 * scale,
    height: 30 * scale,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    top: -6 * scale,
    left: -31 * scale,
  }
})